import 'dart:ui';

import 'package:flutter/material.dart';

class PathHomePage extends StatefulWidget {
  @override
  _PathHomePageState createState() => _PathHomePageState();
}

class _PathHomePageState extends State<PathHomePage>
    with SingleTickerProviderStateMixin {
  // 让矩形动起来
  AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController = new AnimationController(
      vsync: this,
      duration: Duration(seconds: 1),
    );

    // 动画监听
    _animationController.addListener(() {
      setState(() {});
    });

    // 添加动画状态监听
    _animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        // 动画正向执行完毕 重新绘制
        // 重置动画
        _animationController.reset();
        // 正向执行动画
        _animationController.forward();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Path动画"),
      ),
      body: Column(children: <Widget>[
        // 画布
        Expanded(
          child: buildContainer(),
        ),
        // 底部按钮
        Container(
          padding: EdgeInsets.all(40),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () {
                  // 重置动画
                  _animationController.reset();
                  // 正向执行动画
                  _animationController.forward();
                },
                child: Text("开始"),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  _animationController.reset();
                },
                child: Text("结束"),
              ),
            ],
          ),
        ),
      ]),
    );
  }

  buildContainer() {
    return Container(
      // 定义一个画板
      child: CustomPaint(
        painter: PathPainter(_animationController.value),
      ),
    );
  }
}

class PathPainter extends CustomPainter {
  // 绘制进度 0.0--1.0
  double progress = 0.0;
  PathPainter(this.progress);
// 定义画笔
  Paint _paint = new Paint()
    ..color = Colors.blue
    ..style = PaintingStyle.stroke
    ..strokeWidth = 6.0
    ..isAntiAlias = true;

  @override
  void paint(Canvas canvas, Size size) {
    // 画一个矩形
    // 创建一个path

    // 路径中添加矩形
    Path startPath = new Path();
    startPath.addRect(
      Rect.fromCenter(center: Offset(100, 100), width: 100, height: 100),
    );

    // 测量path
    PathMetrics pathMetrics = startPath.computeMetrics();
    // 获取第一小节信息
    PathMetric pathMetric = pathMetrics.first;

    // 测量并裁剪
    Path extraPath = pathMetric.extractPath(0, pathMetric.length * progress);
    // 绘制
    canvas.drawPath(extraPath, _paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // 返回true实时更新
    return true;
    // throw UnimplementedError();
  }
}
